package com.efounder.chat.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.activity.ChatRoomActivity;
import com.efounder.chat.activity.GroupNotifacationActivity;
import com.efounder.chat.activity.NewFriendsActivity;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.ContactTopModel;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseContract;
import com.efounder.frame.baseui.BasePresenterFragment;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import static com.efounder.chat.fragment.ContactsFragment.handleGNQX;
import static com.efounder.frame.utils.Constants.KEY_F_ZGBH;

/**
 * author : zzj
 * e-mail : zhangzhijun@pansoft.com
 * date   : 2018/8/29 13:53
 * desc   : 仿qq的联系人界面
 * version: 1.0
 */
public class XingJIMainFragment extends BasePresenterFragment {

    private String[] mTitle = {"好友","群聊","设备","通讯录","公众号"};
    private TabLayout tabLayout;
    private ViewPager viewPager;

    private LinearLayout topContentLayout;
    private int newFriendCount = 0;
    private int groupNotiveCount = 0;
    List<StubObject> topMenuList = null;
    List<ContactTopModel> topModelList = null;
    LayoutInflater inflater = null;
    private LinearLayout topLayout;//顶部view
    private boolean haveConfigMenu = false;//默认没有配置菜单

    public static XingJIMainFragment newInstance() {

        Bundle args = new Bundle();

        XingJIMainFragment fragment = new XingJIMainFragment();
        fragment.setArguments(args);
        return fragment;
    }
    public XingJIMainFragment(){

    }


    private void initViewPager() {
        // 创建一个集合,装填Fragment
        ArrayList<Fragment> fragments = new ArrayList<>();
        // 装填
        fragments.add(new XingJiMainFriendsFragment());
        fragments.add(new XingJiMainFriendsFragment());
        fragments.add(new XingJiMainFriendsFragment());
        fragments.add(new XingJiMainFriendsFragment());
        fragments.add(new XingJiMainFriendsFragment());

        // 创建ViewPager适配器
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),fragments);
        // 给ViewPager设置适配器
        viewPager.setAdapter(myPagerAdapter);
        // 使用 TabLayout 和 ViewPager 相关联
        tabLayout.setupWithViewPager(viewPager);
        // TabLayout指示器添加文本

    }
    @Override
    protected void initData() {
        super.initData();
        loadTopView();
    }


    @Override
    protected BaseContract.BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.espwechatview_fragment_xingji;
    }

    @Override
    protected void initView(View root) {
        tabLayout = root.findViewById(R.id.tabs);
        viewPager = root.findViewById(R.id.view_pager);
        topContentLayout = root.findViewById(R.id.ll_friend_top_layout);
        initViewPager();
//        setIndicator(mActivity,tabLayout,15,15);
    }

    public class MyPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mFragmentList;


        public MyPagerAdapter(FragmentManager fm,ArrayList<Fragment> fragments) {
            super(fm);
            mFragmentList = fragments;
        }

        @Override
        public Fragment getItem(int position) {

            Fragment fragment = mFragmentList.get(position);

            return fragment;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitle[position];
        }

        @Override
        public int getCount() {

            return mFragmentList.size();
        }
    }

    /**
     * 设置tablayout的导航条宽度
     * @param context
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    public static void setIndicator(Context context, TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout ll_tab = null;
        try {
            ll_tab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) (getDisplayMetrics(context).density * leftDip);
        int right = (int) (getDisplayMetrics(context).density * rightDip);

        for (int i = 0; i < ll_tab.getChildCount(); i++) {
            View child = ll_tab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }
    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric;
    }

    //初始化上面部分的view
    private void loadTopView() {
        topMenuList = Registry.getRegEntryList("Contacts");
        if (topMenuList == null) {
            return;
        }
        inflater = LayoutInflater.from(mActivity);
        //不为null 配置了菜单
        haveConfigMenu = true;

        if (topLayout != null) {
            //移除view 重新初始化
            topLayout.removeAllViews();
        }

        topModelList = new ArrayList<>();
//        topModelList.add(new ContactTopModel("新的朋友", "cicon_xdpy", new StubObject(), "xdpy", newFriendCount));
//        topModelList.add(new ContactTopModel("群聊", "cicon_groupchat", new StubObject(), "ql", 0));
//        topModelList.add(new ContactTopModel("群通知", "cicon_groupnotice", new StubObject(), "qtz", groupNotiveCount));

        handleGNQX(topMenuList);
        for (StubObject stubObject : topMenuList) {
            Hashtable<String, String> hashtable = stubObject.getStubTable();
            ContactTopModel model = new ContactTopModel();
            model.setcName(hashtable.get("caption"));
            model.setGnbh(hashtable.get("id"));
            model.setImage(hashtable.get("menuIcon"));
            model.setBadgeNum(0);
            model.setHashtable(hashtable);
            topModelList.add(model);
            if ("xdpy".equals(stubObject.getString("id", ""))) {
                //新的朋友
                model.setBadgeNum(newFriendCount);
            } else if ("qtz".equals(stubObject.getString("id", ""))) {
                //群通知
                model.setBadgeNum(groupNotiveCount);
            }
        }
        for (ContactTopModel model : topModelList) {
            addItemView(model, inflater);
        }

//        topContentLayout.addView(topLayout);
    }
    private void addItemView(final ContactTopModel model, LayoutInflater inflater) {
        ViewGroup oneLayout = (ViewGroup) inflater.inflate(
                R.layout.contacts_topview, null, false);
        TextView titleView = (TextView) oneLayout.findViewById(R.id.title);
        ImageView avatar = (ImageView) oneLayout.findViewById(R.id.avatar);
        titleView.setText(model.getcName());
        String filepath = AppConstant.APP_ROOT + "/res/unzip_res/menuImage/" + model.getImage();
        LXGlideImageLoader.getInstance().showRoundUserAvatar(getActivity(), avatar,
                "file://" + filepath, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
        //初始化角标
        BadgeView badgeView = new BadgeView(getActivity(), avatar);
        if (model.getBadgeNum() != 0) {
            badgeView.setVisibility(View.VISIBLE);
            badgeView.setBadgeMargin(3);
            badgeView.setTextSize(13);
            badgeView.setTag("badge");
            badgeView.setText(String.valueOf(model.getBadgeNum()));
            badgeView.setBadgeBackgroundColor(getActivity().getResources().getColor(
                    R.color.chat_badge_color));
            badgeView.show();
        } else {
            badgeView.setVisibility(View.GONE);
        }
        oneLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("xdpy".equals(model.getGnbh())) {//新的朋友
                    Intent intent = new Intent(getActivity(), NewFriendsActivity.class);
                    startActivity(intent);
                } else if ("ql".equals(model.getGnbh())) {//群聊
                    Intent intent = new Intent(getActivity(), ChatRoomActivity.class);
                    startActivity(intent);
                } else if ("qtz".equals(model.getGnbh())) {//群通知
                    Intent intent = new Intent(getActivity(), GroupNotifacationActivity.class);
                    startActivity(intent);
                } else {
                    Hashtable table = model.getHashtable();
                    String utype = (String) table.get("utype");
                    String androidShow = (String) table.get("AndroidShow");
                    String enterName = (String) table.get("enterName");

                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    Class<?> clazz = null;
                    try {
                        // clazz = loader.loadClass("com.efounder.SDReactNativeContainerForTZ");
                        clazz = loader.loadClass(androidShow);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (clazz == null) {
                        return;
                    }
                    String zgbh = EnvironmentVariable.getProperty(KEY_F_ZGBH);
                    if (TextUtils.isEmpty(zgbh)) {
                        zgbh = EnvironmentVariable.getUserName();
                    }
                    StubObject stubObject = new StubObject();
                    stubObject.setStubTable(table);
                    try {
                        new AbFragmentManager(getActivity()).startActivity(stubObject, 0, 0);

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (true) {
                        return;
                    }
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("enterName", enterName);
//                    bundle.putSerializable("zgbh", zgbh);
//                    bundle.putSerializable("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
//                    bundle.putSerializable("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
//                    bundle.putSerializable("jsrq", EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ));
//                    bundle.putSerializable("utype", utype);
//                    bundle.putSerializable("title", model.getcName());
//                    Intent intent = new Intent(getActivity(),
//                            clazz);
//                    intent.putExtra("data", bundle);
//                    startActivity(intent);
                }
            }
        });
        topContentLayout.addView(oneLayout);
    }
}
